package com.scwatch.core.web.back;

import com.scwatch.common.orm.RowSide;
import com.scwatch.common.util.RedisTemplateUtils;
import com.scwatch.common.web.Servlets;
import com.scwatch.core.constant.Constants;
import com.scwatch.core.domain.*;
import com.scwatch.core.html.HtmlService;
import com.scwatch.core.service.*;
import com.scwatch.core.support.Backends;
import com.scwatch.core.support.CmsException;
import com.scwatch.core.support.Context;
import com.scwatch.core.thirdapi.UserSystemApi;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.scwatch.core.constant.Constants.*;

/**
 * 报料
 *
 * @author gujianlin
 */
@Controller
@RequestMapping("/core/bao")
public class BaoInfoController {
    private static final Logger logger = LoggerFactory.getLogger(BaoInfoController.class);

    public static final int INCLUDE_CHILDREN = 0;
    public static final int INCLUDE_MULTI = 1;
    public static final int MAIN_NODE = 2;


    /**
     * 查询报料
     * @param queryNodeId 栏目id
     * @param queryNodeType 类型
     * @param queryStatus 状态
     * @param returnUrl 返回url
     * @param pageable 分页
     * @param request 请求对象
     * @param modelMap
     * @return 结果页面
     */
    @RequiresPermissions(value={"core:bao:list",
            "core:bao:audit",
            "core:bao:back",
            "core:bao:audit",
            "core:bao:released",
            "core:bao:published",
            "core:bao:expired",
            "core:bao:draft",
            "core:bao:rejection",
            "core:bao:contribute",
            "core:bao:collect",
            "core:bao:recycle"
    },logical = Logical.OR)
    @RequestMapping("baolist.do")
    public String baolist(Integer queryNodeId, Integer queryNodeType, String queryStatus,
                          String returnUrl,
                          @PageableDefault(sort = {"publishDate", "id"}, direction = Sort.Direction.DESC) Pageable pageable,
                          HttpServletRequest request, org.springframework.ui.Model modelMap) {

        String url = "core/bao/bao_list";
        Integer siteId = Context.getCurrentSiteId();
        User user = Context.getCurrentUser();
        Integer[] nodeIds = getNodeIdsByFlag(Constants.MODEL_FLAG_BAO, siteId);
        Integer nodeId = queryNodeId;
        if (nodeIds != null && nodeIds.length > 0) {
            nodeId = nodeIds[0];
        }
        Node queryNode = null;
        if (queryNodeId != null) {
            queryNode = nodeQuery.get(queryNodeId);
        }

        Map<String, String[]> params = Servlets.getParamValuesMap(request, Constants.SEARCH_PREFIX);


        Page<Info> pagedList = infoQuery.findAll(null, siteId, null, nodeId, null, null, true, 1, queryStatus, params, pageable, nodeIds);
        List<Attribute> attributeList = attributeService.findList(siteId);
        modelMap.addAttribute("pagedList", pagedList);
        modelMap.addAttribute("attributeList", attributeList);
        modelMap.addAttribute("queryNodeId", nodeId);
        modelMap.addAttribute("queryNodeType", queryNodeType);
        modelMap.addAttribute("queryStatus", queryStatus);
        modelMap.addAttribute("node", queryNode);
        modelMap.addAttribute("returnUrl", returnUrl);
        return url;
    }

    /**
     * 查看报料详情
     * @param id
     * @param position
     * @param queryNodeId
     * @param returnUrl
     * @param queryParentId
     * @param queryNodeType
     * @param queryInfoPermType
     * @param queryStatus
     * @param pageable
     * @param request
     * @param modelMap
     * @return
     */
    @RequiresPermissions("core:bao:edit")
    @RequestMapping("baoedit.do")
    public String baoedit(Integer id, Integer position, Integer queryNodeId, String returnUrl, Integer queryParentId,
                          @RequestParam(defaultValue = "0") int queryNodeType, Integer queryInfoPermType, String queryStatus,
                          @PageableDefault(sort = {"publishDate", "id"}, direction = Sort.Direction.DESC) Pageable pageable,
                          HttpServletRequest request, org.springframework.ui.Model modelMap) {
        if (returnUrl == null) {
            returnUrl = "core/bao/bao_form";
        }
        Site site = Context.getCurrentSite();
        User user = Context.getCurrentUser();
        Info bean = infoQuery.get(id);
        Backends.validateDataInSite(bean, site.getId());
        if (!bean.isDataPerm(user)) {
            throw new CmsException("accessDenied");
        }
        Integer nodeId = null;
        Integer mainNodeId = null;
        String treeNumber = null;
        Node queryNode = null;
        if (queryNodeId != null) {
            queryNode = nodeQuery.get(queryNodeId);
        }
        if (queryNode != null) {
            if (queryNodeType == INCLUDE_MULTI) {
                nodeId = queryNodeId;
            } else if (queryNodeType == MAIN_NODE) {
                mainNodeId = queryNodeId;
            } else {
                treeNumber = queryNode.getTreeNumber();
            }
        }
        Map<String, String[]> params = Servlets.getParamValuesMap(request, Constants.SEARCH_PREFIX);
        Integer infoPermType = user.getInfoPermType(site.getId());
        if (queryInfoPermType != null && queryInfoPermType > infoPermType) {
            infoPermType = queryInfoPermType;
        }
        boolean allInfoPerm = user.getAllInfoPerm(site.getId());
        RowSide<Info> side = infoQuery.findSide(site.getId(), mainNodeId, nodeId, treeNumber, user.getId(), allInfoPerm,
                infoPermType, queryStatus, params, bean, position, pageable.getSort());
        modelMap.addAttribute("bean", bean);
        modelMap.addAttribute("side", side);
        modelMap.addAttribute("position", position);

        Node node = bean.getNode();
        Model model = bean.getModel();
        List<Attribute> attrList = attributeService.findList(site.getId());
        List<MemberGroup> groupList = memberGroupService.findList();
        String orgTreeNumber = site.getOrg().getTreeNumber();

        modelMap.addAttribute("model", model);
        modelMap.addAttribute("node", node);
        modelMap.addAttribute("attrList", attrList);
        modelMap.addAttribute("groupList", groupList);
        modelMap.addAttribute("orgTreeNumber", orgTreeNumber);
        modelMap.addAttribute("queryNodeId", queryNodeId);
        modelMap.addAttribute("queryNodeType", queryNodeType);
        modelMap.addAttribute("queryInfoPermType", queryInfoPermType);
        modelMap.addAttribute("queryStatus", queryStatus);
        modelMap.addAttribute(OPRT, EDIT);
        modelMap.addAttribute("queryParentId", queryParentId);
        return returnUrl;
    }

    /**
     * 审核通过
     * @param ids 报料id
     * @param opinion
     * @param position
     * @param queryNodeId 栏目
     * @param queryNodeType 类型
     * @param queryInfoPermType 权限
     * @param queryStatus 状态
     * @param redirect
     * @param request
     * @param ra
     * @return 结果页面
     */
    @RequiresPermissions("core:bao:audit_pass")
    @RequestMapping("baoaudit_pass.do")
    public String baoauditPass(Integer[] ids, String opinion, Integer position, Integer queryNodeId,
                               Integer queryNodeType, Integer queryInfoPermType, String queryStatus, String redirect,
                               HttpServletRequest request, RedirectAttributes ra) {
        Integer siteId = Context.getCurrentSiteId();
        Integer userId = Context.getCurrentUserId();
        validateIds(ids, siteId);
        List<Info> beans = infoService.pass(ids, userId, opinion);
        String ip = Servlets.getRemoteAddr(request);
//        if(ids!=null){
//            service.batchupdateHtmlThread(Arrays.asList(ids),false,"firePostPass");
//        }
      /*  UserSystemApi userSystemApi=new UserSystemApi();
        for (Info bean : beans) {
            if(bean.getIsUse()!=null && bean.getIsUse().equals("1")){
                //调用积分商城系统 增加积分接口
                String apiUserId=bean.getCreator().getUsername();
                String apiToken=redisTemplateUtils.getMapField("accessToken",bean.getCreator().getId().toString());
                String result=userSystemApi.addIntegral(apiUserId,apiToken);
                logger.info("api name:addIntegral param apiUserId:{},apiToken:{},result:{}",apiUserId,apiToken,result);
                logService.operation("api.addIntegral","投稿调用积分商城接口:"+result,"param apiUserId:"+apiToken+",apiToken:"+apiToken+",result:"+result, bean.getId(), ip, userId, siteId);

                logService.operation("opr.info.auditPass", bean.getTitle(), null, bean.getId(), ip, userId, siteId);
                logger.info("audit pass Info, title={}.", bean.getTitle());
            }
        }*/
        ra.addAttribute("queryNodeId", queryNodeId);
        ra.addAttribute("queryNodeType", queryNodeType);
        ra.addAttribute("queryInfoPermType", queryInfoPermType);
        ra.addAttribute("queryStatus", queryStatus);
        ra.addFlashAttribute(MESSAGE, OPERATION_SUCCESS);
//        if (Constants.REDIRECT_EDIT.equals(redirect)) {
//            ra.addAttribute("id", beans.iterator().next().getId());
//            ra.addAttribute("position", position);
//            return "redirect:edit.do";
//        } else if (Constants.REDIRECT_VIEW.equals(redirect)) {
//            ra.addAttribute("id", beans.iterator().next().getId());
//            ra.addAttribute("position", position);
//            return "redirect:view.do";
//        } else {
//            return "redirect:list.do";
//        }
        return "redirect:baolist.do";
    }

    /**
     * 撤销审核
     * @param ids 报料id
     * @param opinion
     * @param position
     * @param queryNodeId 栏目
     * @param queryNodeType 类型
     * @param queryInfoPermType 权限
     * @param queryStatus 状态
     * @param redirect
     * @param request
     * @param ra
     * @return 结果页面
     */
    @RequiresPermissions("core:bao:audit_reject")
    @RequestMapping("baoaudit_reject.do")
    public String baoauditReject(Integer[] ids, String opinion, Integer position, Integer queryNodeId,
                                 Integer queryNodeType, Integer queryInfoPermType, String queryStatus, String redirect,
                                 HttpServletRequest request, RedirectAttributes ra) {
        Integer siteId = Context.getCurrentSiteId();
        Integer userId = Context.getCurrentUserId();
        validateIds(ids, siteId);
        List<Info> beans = infoService.reject(ids, userId, opinion, false);
//        if(ids!=null){
//            service.batchupdateHtmlThread(Arrays.asList(ids),false,"firePostReject");
//        }
        String ip = Servlets.getRemoteAddr(request);
        for (Info bean : beans) {
            logService.operation("opr.info.auditReject", bean.getTitle(), null, bean.getId(), ip, userId, siteId);
            logger.info("audit reject Info, title={}.", bean.getTitle());
        }
        ra.addAttribute("queryNodeId", queryNodeId);
        ra.addAttribute("queryNodeType", queryNodeType);
        ra.addAttribute("queryInfoPermType", queryInfoPermType);
        ra.addAttribute("queryStatus", queryStatus);
        ra.addFlashAttribute(MESSAGE, OPERATION_SUCCESS);
//        if (Constants.REDIRECT_EDIT.equals(redirect)) {
//            ra.addAttribute("id", beans.iterator().next().getId());
//            ra.addAttribute("position", position);
//            return "redirect:edit.do";
//        } else if (Constants.REDIRECT_VIEW.equals(redirect)) {
//            ra.addAttribute("id", beans.iterator().next().getId());
//            ra.addAttribute("position", position);
//            return "redirect:view.do";
//        } else {
//            return "redirect:list.do";
//        }
        return "redirect:baolist.do";
    }

    /**
     * 删除报料
     * @param ids 报料id
     * @param queryNodeId 栏目id
     * @param queryNodeType 类型
     * @param queryInfoPermType 权限
     * @param queryStatus 状态
     * @param request 请求对象
     * @param ra
     * @return 结果页面
     */
    @RequiresPermissions("core:bao:delete")
    @RequestMapping("baodelete.do")
    public String baodelete(Integer[] ids, Integer queryNodeId, Integer queryNodeType, Integer queryInfoPermType,
                            String queryStatus, HttpServletRequest request, RedirectAttributes ra) {
        Site site = Context.getCurrentSite();
        User user = Context.getCurrentUser();
        validateIds(ids, site.getId());
        for (Integer id : ids) {
            Info bean = infoQuery.get(id);
            if (!bean.isDataPerm(user) || !bean.isAuditPerm(user)) {
                throw new CmsException("accessDenied");
            }
        }
        List<Info> beans = infoService.delete(ids);
//        service.batchupdateHtmlThread(Arrays.asList(ids),true,"firePostDelete");
        String ip = Servlets.getRemoteAddr(request);
        for (Info bean : beans) {
            logService
                    .operation("opr.info.delete", bean.getTitle(), null, bean.getId(), ip, user.getId(), site.getId());
            logger.info("delete Info, name={}.", bean.getTitle());
        }
        ra.addAttribute("queryNodeId", queryNodeId);
        ra.addAttribute("queryNodeType", queryNodeType);
        ra.addAttribute("queryInfoPermType", queryInfoPermType);
        ra.addAttribute("queryStatus", queryStatus);
        ra.addFlashAttribute(MESSAGE, DELETE_SUCCESS);
        return "redirect:baolist.do";
    }

    private Integer[] getNodeIdsByFlag(String modelFlag, Integer siteId) {
        Integer[] nodeIds = null;
        Map<String, String[]> paramMap = new HashMap<String, String[]>();
        paramMap.put("EQ_flag", new String[]{modelFlag});
        List<Model> models = modelService.findList(siteId, null, paramMap, null);

        paramMap = new HashMap<String, String[]>();
        String[] idsStr;
        if (models != null && models.size() > 0) {
            idsStr = new String[models.size()];
            for (int i = 0; i < models.size(); i++) {
                idsStr[i] = models.get(i).getId().toString();
            }
            paramMap.put("EQ_nodeModel.id", idsStr);
        }
        Sort paramSort = new Sort(Sort.Direction.ASC, "treeNumber", "id");
        List<Node> currentNodeList = nodeQuery.findList(siteId, null,
                null, null, true,
                paramMap, paramSort);
        if (currentNodeList != null) {
            nodeIds = new Integer[currentNodeList.size()];
            for (int i = 0; i < currentNodeList.size(); i++) {
                nodeIds[i] = (currentNodeList.get(i).getId());
            }
        }
        return nodeIds;
    }

    @ModelAttribute
    public void preloadNodeBean(@RequestParam(required = false) Integer oid, org.springframework.ui.Model modelMap) {
        if (oid != null) {
            Node bean = nodeQuery.get(oid);
            if (bean != null) {
                modelMap.addAttribute("bean", bean);
                NodeDetail detail = bean.getDetail();
                if (detail == null) {
                    detail = new NodeDetail();
                    detail.setId(oid);
                    detail.setNode(bean);
                }
                modelMap.addAttribute("detail", detail);
            }
        }
    }

    @ModelAttribute
    public void preloadInfoBean(@RequestParam(required = false) Integer oid, org.springframework.ui.Model modelMap) {
        if (oid != null) {
            Info bean = infoQuery.get(oid);
            if (bean != null) {
                modelMap.addAttribute("bean", bean);
                InfoDetail detail = bean.getDetail();
                if (detail == null) {
                    detail = new InfoDetail();
                    detail.setId(oid);
                    detail.setInfo(bean);
                }
                modelMap.addAttribute("detail", detail);
            }
        }
    }

    private void validateIds(Integer[] ids, Integer siteId) {
        for (Integer id : ids) {
            Backends.validateDataInSite(nodeQuery.get(id), siteId);
        }
    }

    private Integer[] getInfoPermIds(Integer siteId, Integer parentId) {
        Collection<Role> roles = null;
        if (parentId != null) {
            Node node = nodeQuery.get(parentId);
            if (node != null) {
                roles = node.getInfoPerms();
            }
        }
        if (roles == null) {
            roles = roleService.findList(siteId);
        }
        int len = roles.size();
        Integer[] ids = new Integer[len];
        int i = 0;
        for (Role role : roles) {
            ids[i++] = role.getId();
        }
        return ids;
    }

    private Integer[] getNodePermIds(Integer siteId, Integer parentId) {
        Collection<Role> roles = null;
        if (parentId != null) {
            Node node = nodeQuery.get(parentId);
            if (node != null) {
                roles = node.getNodePerms();
            }
        }
        if (roles == null) {
            roles = roleService.findList(siteId);
        }
        int len = roles.size();
        Integer[] ids = new Integer[len];
        int i = 0;
        for (Role role : roles) {
            ids[i++] = role.getId();
        }
        return ids;
    }

    private Integer[] getViewGroupIds(Integer siteId, Integer parentId) {
        Collection<MemberGroup> groups = null;
        if (parentId != null) {
            Node node = nodeQuery.get(parentId);
            if (node != null) {
                groups = node.getViewGroups();
            }
        }
        if (groups == null) {
            groups = memberGroupService.findList();
        }
        int len = groups.size();
        Integer[] ids = new Integer[len];
        int i = 0;
        for (MemberGroup group : groups) {
            ids[i++] = group.getId();
        }
        return ids;
    }

    private Integer[] getContriGroupIds(Integer siteId, Integer parentId) {
        Collection<MemberGroup> groups = null;
        if (parentId != null) {
            Node node = nodeQuery.get(parentId);
            if (node != null) {
                groups = node.getContriGroups();
            }
        }
        if (groups == null) {
            groups = memberGroupService.findList();
        }
        int len = groups.size();
        Integer[] ids = new Integer[len];
        int i = 0;
        for (MemberGroup group : groups) {
            ids[i++] = group.getId();
        }
        return ids;
    }

    private Integer[] getCommentGroupIds(Integer siteId, Integer parentId) {
        Collection<MemberGroup> groups = null;
        if (parentId != null) {
            Node node = nodeQuery.get(parentId);
            if (node != null) {
                groups = node.getCommentGroups();
            }
        }
        if (groups == null) {
            groups = memberGroupService.findList();
        }
        int len = groups.size();
        Integer[] ids = new Integer[len];
        int i = 0;
        for (MemberGroup group : groups) {
            ids[i++] = group.getId();
        }
        return ids;
    }

    private String[] splitTagKeywords(String tagKeywords) {
        String split = Constants.TAG_KEYWORDS_SPLIT;
        if (StringUtils.isNotBlank(split)) {
            for (int i = 0, len = split.length(); i < len; i++) {
                tagKeywords = StringUtils.replace(tagKeywords, String.valueOf(split.charAt(i)), ",");
            }
        }
        return StringUtils.split(tagKeywords, ',');
    }

    @Autowired
    private OperationLogService logService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private MemberGroupService memberGroupService;
    @Autowired
    private WorkflowService workflowService;
    @Autowired
    private ModelService modelService;
    @Autowired
    private NodeService nodeService;
    @Autowired
    private NodeQueryService nodeQuery;
    @Autowired
    private AttributeService attributeService;
    @Autowired
    private InfoQueryService infoQuery;
    @Autowired
    private InfoService infoService;
    @Autowired
    private HtmlService htmlService;
    @Autowired
    private InfoNodeService infoNodeService;
    @Autowired
    private FlashBigNewService flashBigNewService;
    @Autowired
    private RedisTemplateUtils redisTemplateUtils;


}
